package com.xjcs.saplingplan.room.bean.countdown

import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import com.nlf.calendar.Lunar
import com.nlf.calendar.LunarMonth
import com.nlf.calendar.LunarYear
import com.nlf.calendar.Solar
import com.xjcs.saplingplan.const.CountdownRepeatType
import com.xjcs.saplingplan.utils.FesLibUtils
import com.xjcs.saplingplan.utils.TimeUtils
import com.xjcs.saplingplan.utils.TimeUtils.FORMAT_D
import com.xjcs.saplingplan.utils.TimeUtils.FORMAT_MD_TEXT
import com.xjcs.saplingplan.utils.TimeUtils.FORMAT_YMD_TEXT
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale
import kotlin.math.abs
import kotlin.math.min

@Entity
class CountdownBean {

    @PrimaryKey
    var countdownId = ""    //倒数日Id
    var countdownType = 0  //倒数日0、纪念日1、生日2、节日3
    var countdownUserId = ""    //用户Id
    var countdownTitle = "" //倒数日标题
    var countdownCateName = ""   //倒数日分类名称
    var countdownDateMillis = 0L //倒数日目标日时间戳
    var countdownDate = "" //倒数日目标日
    var countdownRepeatType = 0    //倒数日重复类型    0-无重复 1-周 2-月 3-年
    var countdownRemind = ""    //提醒时间
    var countdownRemindDays = ""    //提醒提前天数
    var countdownBg = ""        //背景图片
    var countdownDateType = "solar" //solar-公历 lunar-农历

    var countHiddenYear = false

    var countdownCode = ""      //是否是节日库

    var createTimeMillis = 0    //创建时间
    var updateTimeMillis = 0    //更新时间

    var countdownTopStatus = 0  //是否置顶 0-不置顶 1-置顶

    var updateStatus = 1        //是否需要上传 0-不需要 1-需要


    @Ignore
    var targetDateStr = ""

    @Ignore
    var targetDay = 0

    /**
     * 获取类型
     */
    fun getTypeStr(): String {
        return when (countdownType) {
            0 -> {
                "倒数日"
            }

            1 -> {
                "纪念日"
            }

            2 -> {
                "生日"
            }

            3 -> {
                "节日"
            }

            else -> {
                "倒数日"
            }
        }
    }

    /**
     * 是否是生日
     */
    fun isBirthday(): Boolean {
        return countdownType == 2
    }

    /**
     * 判断是否是农历
     */
    fun isLunar(): Boolean {
        return countdownDateType == "lunar"
    }

    /**
     * 格式化创建倒数日日期
     */
    fun formatSelectDate(timeInMillis: Long, countdownBean: CountdownBean): String {
        if (timeInMillis == 0L || countdownDate.isEmpty()) return ""
        val targetDate = LocalDate.parse(countdownDate)
        val targetSolar = Solar(
            targetDate.year,
            targetDate.monthValue,
            targetDate.dayOfMonth
        )
        val formatDate = TimeUtils.formatDate(timeInMillis, FORMAT_YMD_TEXT)
        return when (countdownBean.countdownRepeatType) {
            CountdownRepeatType.NONE.value -> {
                if (isLunar()) {
                    val targetLunar = targetSolar.lunar
                    "${targetLunar.yearInChinese}年${targetLunar.monthInChinese}月" + targetLunar.dayInChinese
                } else {
                    formatDate
                }
            }

            CountdownRepeatType.WEEK.value -> {
                val sdf = SimpleDateFormat("EE", Locale.CHINA)
                val weekDay = sdf.format(Date(timeInMillis))
                "${formatDate}(每${weekDay})"
            }

            CountdownRepeatType.MONTH.value -> {
                "${formatDate}(每月${TimeUtils.formatDate(timeInMillis, FORMAT_D)}日)"
            }

            CountdownRepeatType.YEAR.value -> {
                "${formatDate}(每年${TimeUtils.formatDate(timeInMillis, FORMAT_MD_TEXT)})"
            }

            else -> {
                formatDate
            }
        }
    }

    /**
     * 将目标日期格式化、计算剩余天数
     */
    fun getTargetDateStr(todaySolar: Solar, todayLunar: Lunar): Pair<String, Int> {
        val targetStr: String
        val targetRestDay: Int
        if (countdownCode.isNotEmpty() && countdownDate.isEmpty()) {
            //节日库
            val pairTarget = FesLibUtils.getDateByCode(countdownCode, todaySolar)
            targetStr = pairTarget.first
            targetRestDay = pairTarget.second
        } else {
            val targetDate = LocalDate.parse(countdownDate)
            var targetSolar = Solar(
                targetDate.year,
                targetDate.monthValue,
                targetDate.dayOfMonth
            )
            when (countdownRepeatType) {
                CountdownRepeatType.YEAR.value -> { //每年重复
                    if (isLunar()) {
                        //阳历转阴历
                        val targetLunar = targetSolar.lunar
                        val targetYmdLunar = if (targetLunar.month < 0) {
                            //当年闰月是几月
                            val leapMonth = LunarYear(todayLunar.year).leapMonth

                            val curYearLunar = if (leapMonth == targetLunar.month) {
                                val monthDay =
                                    LunarMonth.fromYm(todayLunar.year, targetLunar.month).dayCount
                                Lunar(
                                    todayLunar.year,
                                    targetLunar.month,
                                    min(targetLunar.day, monthDay)
                                )
                            } else {
                                val monthDay =
                                    LunarMonth.fromYm(todayLunar.year, -targetLunar.month).dayCount
                                Lunar(
                                    todayLunar.year,
                                    -targetLunar.month,
                                    min(targetLunar.day, monthDay)
                                )
                            }

                            val curMonth = abs(curYearLunar.month)
                            val todayMonth = abs(todayLunar.month)
                            if (curMonth > todayMonth ||
                                (curMonth == todayMonth && curYearLunar.day >= todayLunar.day)
                            ) {
                                curYearLunar
                            } else {
                                //下一年闰月
                                val nextMonth = LunarYear(todayLunar.year + 1).leapMonth
                                if (nextMonth == targetLunar.month) {
                                    val monthDay = LunarMonth.fromYm(
                                        todayLunar.year + 1,
                                        -targetLunar.month
                                    ).dayCount
                                    Lunar(
                                        todayLunar.year + 1,
                                        -targetLunar.month,
                                        min(targetLunar.day, monthDay)
                                    )
                                } else {
                                    val monthDay = LunarMonth.fromYm(
                                        todayLunar.year + 1,
                                        targetLunar.month
                                    ).dayCount
                                    Lunar(
                                        todayLunar.year + 1,
                                        targetLunar.month,
                                        min(targetLunar.day, monthDay)
                                    )
                                }
                            }
                        } else {
                            if (targetLunar.month > todayLunar.month ||
                                (targetLunar.month == todayLunar.month && targetLunar.day >= todayLunar.day)
                            ) {
                                targetLunar
                            } else {
                                val monthDay = LunarMonth.fromYm(
                                    targetLunar.year + 1,
                                    targetLunar.month
                                ).dayCount
                                Lunar(
                                    targetLunar.year + 1,
                                    targetLunar.month,
                                    min(todayLunar.day, monthDay)
                                )
                            }
                        }
                        targetStr =
                            "${targetYmdLunar.yearInChinese}年${targetYmdLunar.monthInChinese}月" + targetYmdLunar.dayInChinese
                        targetRestDay = targetYmdLunar.solar.subtract(targetLunar.solar)
                    } else {
                        //公历
                        if (targetSolar.isBefore(todaySolar)) {
                            targetSolar = if (targetSolar.year == todaySolar.year) {
                                targetSolar.nextYear(1)
                            } else {
                                targetSolar.nextYear(todaySolar.year - targetSolar.year)
                            }
                        }
                        targetStr =
                            "${targetSolar.year}年${targetSolar.month}月${targetSolar.day}日"
                        targetRestDay = targetSolar.subtract(todaySolar)
                    }
                }

                CountdownRepeatType.MONTH.value -> {
                    //每月重复
                    if (isLunar()) {
                        //阳历转阴历
                        val targetLunar = targetSolar.lunar
                        val targetYmdLunar = if (targetLunar.solar.isBefore(todaySolar)) {
                            if (targetLunar.day >= todayLunar.day) {
                                val monthDay =
                                    LunarMonth.fromYm(todayLunar.year, todayLunar.month).dayCount
                                Lunar(
                                    todayLunar.year,
                                    todayLunar.month,
                                    min(targetLunar.day, monthDay)
                                )
                            } else {
                                //当年闰月是几月
                                val leapMonth = LunarYear(todayLunar.year).leapMonth
                                if (todayLunar.month == leapMonth) {
                                    val monthDay =
                                        LunarMonth.fromYm(
                                            todayLunar.year,
                                            -todayLunar.month
                                        ).dayCount
                                    //下个月是闰月
                                    Lunar(
                                        todayLunar.year,
                                        -todayLunar.month,
                                        min(targetLunar.day, monthDay)
                                    )
                                } else {
                                    //下个月不是闰月
                                    if (todayLunar.month == 12) {
                                        val monthDay =
                                            LunarMonth.fromYm(todayLunar.year + 1, 1).dayCount
                                        Lunar(
                                            todayLunar.year + 1,
                                            1,
                                            min(targetLunar.day, monthDay)
                                        )
                                    } else {
                                        val monthDay =
                                            LunarMonth.fromYm(
                                                todayLunar.year,
                                                abs(todayLunar.month) + 1
                                            ).dayCount
                                        Lunar(
                                            todayLunar.year,
                                            abs(todayLunar.month) + 1,
                                            min(targetLunar.day, monthDay)
                                        )
                                    }
                                }
                            }
                        } else {
                            targetLunar
                        }
                        targetStr =
                            "${targetYmdLunar.yearInChinese}年${targetYmdLunar.monthInChinese}月" + targetYmdLunar.dayInChinese
                        targetRestDay = targetYmdLunar.solar.subtract(targetLunar.solar)
                    } else {
                        //公历
                        if (targetSolar.isBefore(todaySolar)) {
                            targetSolar = if (targetSolar.month == todaySolar.month) {
                                targetSolar.nextMonth(1)
                            } else {
                                targetSolar.nextMonth(todaySolar.month - targetSolar.month)
                            }
                        }
                        targetStr =
                            "${targetSolar.year}年${targetSolar.month}月${targetSolar.day}日"
                        targetRestDay = targetSolar.subtract(todaySolar)
                    }
                }

                CountdownRepeatType.WEEK.value -> {
                    //每周重复
                    if (targetSolar.isBefore(todaySolar)) {
                        targetSolar = targetSolar.next(7)
                    }
                    if (isLunar()) {
                        //阳历转阴历
                        val targetLunar = targetSolar.lunar
                        targetStr =
                            "${targetLunar.yearInChinese}年${targetLunar.monthInChinese}月" + targetLunar.dayInChinese
                    } else {
                        targetStr =
                            "${targetSolar.year}年${targetSolar.month}月${targetSolar.day}日"
                    }
                    targetRestDay = targetSolar.subtract(todaySolar)
                }

                else -> {
                    targetRestDay = targetSolar.subtract(todaySolar)
                    targetStr = if (isLunar()) {
                        val targetYmdLunar = targetSolar.lunar
                        "${targetYmdLunar.yearInChinese}年${targetYmdLunar.monthInChinese}月" + targetYmdLunar.dayInChinese
                    } else {
                        targetDate.format(DateTimeFormatter.ofPattern(FORMAT_YMD_TEXT))
                    }
                }
            }
        }
        return Pair(targetStr, targetRestDay)
    }

    /**
     * 提醒
     */
    fun getRemindStr(): String {
        return if (countdownRemindDays.isEmpty()) "无" else {
            val dayList = countdownRemindDays.split(",")
            if (dayList.isEmpty()) {
                "无"
            } else {
                var text = ""
                dayList.forEach {
                    text += if (it == "0") {
                        ",当天"
                    } else {
                        ",提前${it}天"
                    }
                }
                text = text.substring(1).replace(",", "/")
                text += " $countdownRemind"
                text
            }
        }
    }

}